package com.quanquan.api;

import com.alibaba.fastjson.JSONObject;
import com.quanquan.common.Response;
import com.quanquan.entity.LessonInfo;
import com.quanquan.entity.StudentInfo;
import com.quanquan.entity.StudentLesson;
import com.quanquan.service.LessonInfoService;
import com.quanquan.service.StudentInfoService;
import com.quanquan.service.StudentLessonService;
import com.quanquan.utils.ExcelUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping(value = "/api/lesson")
public class LessonInfoContrller {

    @Autowired
    private LessonInfoService lessonInfoService;
    @Autowired
    private StudentLessonService studentLessonService;
    @Autowired
    private StudentInfoService studentInfoService;

    /**
     * 选课详情
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/choose", method = RequestMethod.GET)
    @ResponseBody
    public Response choose (Long studentId) throws Exception{
        if (studentId == null || studentId < 0) {
            return new Response().failure("id不正确");
        }
        StudentLesson studentLesson = studentLessonService.findByStudentId(studentId);
        if (studentLesson != null) {
            return new Response().success(studentLesson);
        }
        return new Response().success(studentLesson);
    }

//    @RequestMapping(value = "/import", method = RequestMethod.GET)
//    @ResponseBody
//    public Response importStudent () throws Exception{
//
////        for(Integer k = 169; k <= 187; k++) {
////            String filePath = "E:\\self-work\\运康中学选课系统\\chuer\\" + k.toString() + ".xlsx";
////            // 构造 XSSFWorkbook 对象，strPath 传入文件路径
////            XSSFWorkbook xwb = new XSSFWorkbook(filePath);
////            // 读取第一章表格内容
////            XSSFSheet sheet = xwb.getSheetAt(0);
////            // 定义 row、cell
////            XSSFRow row = null;
////            String cell = null;
////            // 循环输出表格中的内容
////            for (int i = 2; i < sheet.getPhysicalNumberOfRows(); i++) {
////                StudentInfo studentInfo = new StudentInfo();
////                row = sheet.getRow(i);
////                for (int j = row.getFirstCellNum(); j < row.getPhysicalNumberOfCells(); j++) {
////                    // 通过 row.getCell(j).toString() 获取单元格内容，
////                    row.getCell(j).setCellType(HSSFCell.CELL_TYPE_STRING);
////                    cell = row.getCell(j).toString();
////                    if (j == 1) {
////                        studentInfo.setName(cell);
////                    }
////                    if (j == 2) {
////                        studentInfo.setClassName(cell);
////                    }
////                    if (j == 3) {
////                        studentInfo.setMobile(cell);
////                    }
////                }
////                studentInfo.setGrade("chuer");
////                studentInfoService.save(studentInfo);
////            }
////        }
//            String filePath = "E:\\self-work\\最终表格.xlsx";
//            // 构造 XSSFWorkbook 对象，strPath 传入文件路径
//            XSSFWorkbook xwb = new XSSFWorkbook(filePath);
//            // 读取第一章表格内容
//            XSSFSheet sheet = xwb.getSheetAt(0);
//            // 定义 row、cell
//            XSSFRow row = null;
//            String cell = null;
//            // 循环输出表格中的内容
//            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
//                LessonInfo lessonInfo = new LessonInfo();
//                row = sheet.getRow(i);
//                for (int j = row.getFirstCellNum(); j < row.getPhysicalNumberOfCells(); j++) {
//                    // 通过 row.getCell(j).toString() 获取单元格内容，
//                    row.getCell(j).setCellType(HSSFCell.CELL_TYPE_STRING);
//                    cell = row.getCell(j).toString();
//                    if (j == 1) {
//                        lessonInfo.setLessonName(cell);
//                    }
//                    if (j == 2) {
//                        if ("1".equals(cell)) {
//                            lessonInfo.setGrade("chuyi");
//                        }
//                        if ("2".equals(cell)) {
//                            lessonInfo.setGrade("chuer");
//                        }
//                        if ("3".equals(cell)) {
//                            lessonInfo.setGrade("chuyi,chuer");
//                        }
//                    }
//                    if (j == 3) {
//                        lessonInfo.setTeacherName(cell);
//                    }
//                    if (j == 4) {
//                        lessonInfo.setLessonClass(cell);
//                    }
//                    if (j == 5) {
//                        lessonInfo.setRate(cell);
//                    }
//                    if (j == 6) {
//                        lessonInfo.setTeacherType(cell);
//                    }
//                    if (j == 7) {
//                        lessonInfo.setLimitNum(Integer.valueOf(cell));
//                    }
//                    if (j == 8) {
//                        if (lessonInfo.getLessonName().contains("+")) {
//                            lessonInfo.setTeacherMoible(cell + "," + row.getCell(j+1).toString());
//                        } else {
//                            lessonInfo.setTeacherMoible(cell);
//                        }
//                    }
//                }
//                lessonInfoService.save(lessonInfo);
//            }
//        return new Response().success();
//    }

    /**
     * 课程列表
     * @param grade
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Response list (String grade, String name, Integer pn, Integer ps) throws Exception{
        if (pn < 1) {
            return new Response().failure("页数必须大于零");
        }
        if (StringUtils.isNotBlank(name)) {
            List<LessonInfo> lessonNameLike = lessonInfoService.findKeywords(name);
            Map<String, Object> data = new HashMap<>();
            data.put("total", lessonNameLike.size());
            data.put("list", lessonNameLike);
            return new Response().success(data);
        }
//        List<LessonInfo> lessonInfoList = new ArrayList<>();
//        if (pn == null || pn == 0) {
//            lessonInfoList = lessonInfoService.findLesson(grade,0L);
//        } else {
//            lessonInfoList = lessonInfoService.findLesson(grade,(pn-1)*10L);
//        }
        Pageable pageable = new PageRequest(pn - 1 ,ps, Sort.Direction.ASC,"id");
        Page<LessonInfo> page = lessonInfoService.findByGradeLike("%" + grade + "%",pageable);
        Long total = lessonInfoService.countLesson(grade);
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("list", page.getContent());
        return new Response().success(data);
    }

    /**
     * 课程详情
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Response detail (@PathVariable Long id, String token) throws Exception{
        if (id == null || id < 0) {
            return new Response().failure("不存在该课程！");
        }
        LessonInfo lessonInfo = lessonInfoService.findById(id);
        return new Response().success(lessonInfo);
    }

    /**
     * 选课
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/select", method = RequestMethod.POST)
    @ResponseBody
    public Response post (String studentName, String studentClass, String contactWay, Long studentId, Long lessonId) throws Exception{
        if (StringUtils.isBlank(studentName)) {
            return new Response().failure("学生姓名不能为空！");
        }
        if (StringUtils.isBlank(studentClass)) {
            return new Response().failure("自然班级不能为空！");
        }
        if (StringUtils.isBlank(contactWay)) {
            return new Response().failure("联系方式不能为空！");
        }
        if (lessonId == null || lessonId < 0) {
            return new Response().failure("课程不能为空！");
        }
        LessonInfo lessonInfo = lessonInfoService.findById(lessonId);
        if (lessonInfo == null) {
            return new Response().failure("该课程不存在");
        }
        if (studentLessonService.findByStudentId(studentId) != null) {
            return new Response().failure("该学生已经选课成功");
        }
        if (lessonInfo.getNum() >= lessonInfo.getLimitNum()) {
            return new Response().failure("选课人数已满！");
        }
        StudentInfo studentInfo = studentInfoService.findByMobile(contactWay);
        if (!lessonInfo.getGrade().contains(studentInfo.getGrade())) {
            return new Response().failure("选课年级不匹配！");
        }
        if ("chuyi,chuer".equals(lessonInfo.getGrade())) {
            if (studentLessonService.countByGradeAndLessonId(studentInfo.getGrade(), lessonId) >= lessonInfo.getLimitNum()/2) {
                return new Response().failure("该年级人数已选够！");
            }
        }
//        if ("chuyi".equals(studentInfo.getGrade())) {
//            Long now = System.currentTimeMillis();
//            if (now < 1537574400000L || now > 1537632000000L) {
//                return new Response().failure("该时间段初一学生无法选课");
//            }
//        }
//        if ("chuer".equals(studentInfo.getGrade())) {
//            Long now = System.currentTimeMillis();
//            if (now < 1537660800000L || now > 1537718400000L) {
//                return new Response().failure("该时间段初二学生无法选课");
//            }
//        }
        if (studentInfo == null) {
            return new Response().failure("该手机号无法选课！");
        }
        if (!lessonInfo.getGrade().contains(studentInfo.getGrade())) {
            return new Response().failure("只能填报本年级课程！");
        }
        if (!studentInfo.getClassName().equals(studentClass)) {
            return new Response().failure("请选择正确的班级！");
        }
        if (!studentInfo.getMobile().equals(contactWay)) {
            return new Response().failure("请输入正确的手机号！");
        }
        StudentLesson studentLesson = new StudentLesson();
        studentLesson.setLessonId(lessonId);
        studentLesson.setStudentId(studentInfo.getId());
        studentLesson.setStudentName(studentName);
        studentLesson.setStudentClass(studentClass);
        studentLesson.setContactWay(contactWay);
        studentLesson.setGrade(studentInfo.getGrade());
        studentLessonService.save(studentLesson);
        lessonInfo.setNum(lessonInfo.getNum() + 1);
        lessonInfoService.save(lessonInfo);
        Map<String, Object> data = new HashMap<>();
        data.put("student", studentInfo);
        data.put("lesson", lessonInfo);
        return new Response().success(data);
    }

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public Response allLessonList () {
        List<LessonInfo> lessonInfoList = lessonInfoService.findAll();
        Map<String, Object> data = new HashMap<>();
        data.put("total", lessonInfoList.size());
        data.put("list", lessonInfoList);
        return new Response().success(data);
    }

    @RequestMapping(value = "/student", method = RequestMethod.GET)
    @ResponseBody
    public Response allLessonList (String grade, Long id) {
        List<StudentLesson> studentLessonList = null;
        if (grade != null) {
            studentLessonList = studentLessonService.findByLessonIdAndGrade(id, grade);
        } else {
            studentLessonList = studentLessonService.findByLessonId(id);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("total", studentLessonList.size());
        data.put("list", studentLessonList);
        return new Response().success(data);
    }

    @RequestMapping(value = "/notselect", method = RequestMethod.GET)
    @ResponseBody
    public Response notselect (String grade, Long id) {
        List<StudentInfo> studentInfoList = studentInfoService.findByGrade(grade);
        List<StudentInfo> notselect = new ArrayList<>();
        for (StudentInfo studentInfo : studentInfoList) {
            if (studentLessonService.findByStudentId(studentInfo.getId()) == null) {
                notselect.add(studentInfo);
            }
        }
        for (StudentInfo student : notselect) {
            System.out.println(student.getId() + "              " + student.getName() + "       " + student.getClassName() + "               " + student.getMobile());
        }
        return new Response().success();
    }

    @RequestMapping(value = "/export", method = RequestMethod.GET)
    @ResponseBody
    public Response export (HttpServletRequest request, String grade, Long id) {
        List<LessonInfo> lessonInfoList = lessonInfoService.findAll();
        List<String> cols = new ArrayList<>();
        cols.add("学生姓名");
        cols.add("班级");
        cols.add("年级");
        cols.add("手机号");
        cols.add("手机号对应姓名");
        for (LessonInfo lessonInfo : lessonInfoList) {
            String name = lessonInfo.getLessonName() + "报名人数" + lessonInfo.getNum() + "班级容量" + lessonInfo.getLimitNum();
            List<Object[]> dataList = new ArrayList<>();
            List<StudentLesson> studentLessonList = studentLessonService.findByLessonId(lessonInfo.getId());
            for (StudentLesson studentLesson : studentLessonList) {
                Object[] userData = new Object[cols.size()];
                userData[0] = studentLesson.getStudentName();
                userData[1] = studentLesson.getStudentClass();
                if ("chuyi".equals(studentLesson.getGrade())) {
                    userData[2] = "初一";
                }
                if ("chuer".equals(studentLesson.getGrade())) {
                    userData[2] = "初二";
                }
                userData[3] = studentLesson.getContactWay();
                StudentInfo studentInfo = studentInfoService.findById(studentLesson.getStudentId());
                userData[4] = studentInfo.getName();
                dataList.add(userData);
            }
            ExcelUtils.exportXLSRecord(request, dataList, name, cols);
        }
        return new Response().success();
    }

    @RequestMapping(value = "/exportList", method = RequestMethod.GET)
    @ResponseBody
    public Response exportList (HttpServletRequest request, String grade, Long id) {
        List<LessonInfo> lessonInfoList = lessonInfoService.findAll();
        List<String> cols = new ArrayList<>();
        cols.add("课程名称");
        cols.add("组");
        cols.add("老师姓名");
        cols.add("老师手机号");
        cols.add("报名人数");
        cols.add("班级容量");
        String name = "课程报名情况汇总表";
        List<Object[]> dataList = new ArrayList<>();
        for (LessonInfo lessonInfo : lessonInfoList) {
            Object[] userData = new Object[cols.size()];
            userData[0] = lessonInfo.getLessonName();
            userData[1] = lessonInfo.getLessonClass();
            userData[2] = lessonInfo.getTeacherName();
            userData[3] = lessonInfo.getTeacherMoible();
            userData[4] = lessonInfo.getNum();
            userData[5] = lessonInfo.getLimitNum();
            dataList.add(userData);
        }
        ExcelUtils.exportXLSRecord(request, dataList, name, cols);
        return new Response().success();
    }

    @RequestMapping(value = "/exportByClass", method = RequestMethod.GET)
    @ResponseBody
    public Response exportByClass (HttpServletRequest request, String grade, Long id) {
        List<LessonInfo> lessonInfoList = lessonInfoService.findAll();
        List<String> cols = new ArrayList<>();
        cols.add("学生姓名");
        cols.add("班级");
        cols.add("年级");
        cols.add("手机号");
        cols.add("手机号对应姓名");
        cols.add("课程名称");
        for(Integer i = 169; i <=207; i++) {
            String name = i.toString() + "班报名情况";
            List<Object[]> dataList = new ArrayList<>();
            List<StudentLesson> studentLessonList = studentLessonService.findByStudentClass(i.toString());
            for (StudentLesson studentLesson : studentLessonList) {
                Object[] userData = new Object[cols.size()];
                userData[0] = studentLesson.getStudentName();
                userData[1] = studentLesson.getStudentClass();
                if ("chuyi".equals(studentLesson.getGrade())) {
                    userData[2] = "初一";
                }
                if ("chuer".equals(studentLesson.getGrade())) {
                    userData[2] = "初二";
                }
                userData[3] = studentLesson.getContactWay();
                StudentInfo studentInfo = studentInfoService.findById(studentLesson.getStudentId());
                userData[4] = studentInfo.getName();
                LessonInfo lessonInfo = lessonInfoService.findById(studentLesson.getLessonId());
                userData[5] = lessonInfo.getLessonName();
                dataList.add(userData);
            }
            ExcelUtils.exportXLSRecord(request, dataList, name, cols);
        }
        return new Response().success();
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for (Integer i = 169; i <= 207; i++) {
            list.add(i.toString());
        }
        System.out.println(JSONObject.toJSONString(list));
    }
}
